package com.zscat.mallplus.dms.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zscat.mallplus.dms.entity.DmsOrder;
import com.zscat.mallplus.dms.service.IDeviceService;
import com.zscat.mallplus.dms.service.IMealService;
import com.zscat.mallplus.dms.service.IQsgStoreService;
import com.zscat.mallplus.dms.service.WxMsgService;
import com.zscat.mallplus.qsg.*;
import com.zscat.mallplus.qsg.mapper.QsgDeviceMapper;
import com.zscat.mallplus.sys.mapper.SysAppletSetMapper;
import com.zscat.mallplus.ums.entity.SysAppletSet;
import com.zscat.mallplus.ums.entity.UmsAdminMember;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.ums.service.IUmsAdminMemberService;
import com.zscat.mallplus.ums.service.IUmsMemberService;
import com.zscat.mallplus.ums.service.RedisService;
import com.zscat.mallplus.utils.DateUtil;
import com.zscat.mallplus.utils.TemplateData;
import com.zscat.mallplus.utils.WXSubscribeMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@EnableAsync
@Service
public class WxMsgServiceImpl implements WxMsgService {

//    @Value("${wxpay.appId}")
//    private String wxH5Appid;
//    @Value("${wxpay.appSecret}")
//    private String wxH5Secret;
    @Autowired
    private IUmsAdminMemberService adminMemberService;
    @Autowired
    private IMealService mealService;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IUmsMemberService memberService;
    @Autowired
    private IQsgStoreService storeService;

    @Value("${wxpay.appId}")
    private String wxH5Appid;

    @Value("${wxpay.appSecret}")
    private String wxH5Secret;

    @Value("${wxpay.domain}")
    private String wxpayDomain;

    @Resource
    private RedisService redisService;

    @Async
    @Override
    public void sendSubscribeMsg(DmsOrder order) {
        String accessToken = null;
        try {
            QsgStore store = storeService.getById(order.getStoreId());
            QueryWrapper qw = new QueryWrapper();
            qw.eq("store_id",order.getStoreId());
            List<UmsAdminMember> members = adminMemberService.list(qw);
            accessToken = redisService.get("wx_accesstoken");
            String templateId = store.getTemplateIdNew();
            Map<String, TemplateData> param = new HashMap<>();
//            QsgDevice device = deviceService.getById(order.getDeviceId());
//            String first = "您的房间["+device.getMachineName()+"]有一个新订单";
            if (null!=members&&members.size()>0){
                for (UmsAdminMember member : members
                ) {
//                    param.put("first", new TemplateData(first, "#565656"));
                    param.put("thing7", new TemplateData(order.getMealName(), "#565656"));
                    param.put("character_string18", new TemplateData(order.getOrderSn(), "#565656"));
                    param.put("amount4", new TemplateData(order.getPrice().toString(), "#565656"));
                    param.put("time5", new TemplateData(DateUtil.dateToString(order.getCreateDatetime()), "#565656"));
                    param.put("phrase8", new TemplateData(order.getPayType().intValue() == 0?"金额":"积分", "#565656"));
                    String notifyUrl = wxpayDomain + "pages/order/orderDetail?orderId="+order.getId();
                    URLEncoder.encode(notifyUrl,"utf-8");
                    JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(param));
                    String suc = WXSubscribeMsgUtil.sendWechatMsgToUser(member.getWeixinOpenid(), templateId, notifyUrl, jsonObject, accessToken);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Async
    @Override
    public void sendCannelMsg(DmsOrder order) {
        QsgStore store = storeService.getById(order.getStoreId());
        String accessToken = null;
        try {
            QueryWrapper qw = new QueryWrapper();
            qw.eq("store_id",order.getStoreId());
            List<UmsAdminMember> members = adminMemberService.list(qw);
            accessToken = redisService.get("wx_accesstoken");
            String templateId = store.getTemplateIdCancel();
            Map<String, TemplateData> param = new HashMap<>();
            String time = order.getStartTime();
            QsgMeal meal = mealService.getById(order.getMealId());
            if (null!=members&&members.size()>0){
                for (UmsAdminMember member : members
                ) {
//                    param.put("first", new TemplateData("用户取消预约订单", "#565656"));
                    param.put("character_string2", new TemplateData(order.getOrderSn(), "#565656"));
                    param.put("time3", new TemplateData(time, "#565656"));
                    param.put("short_thing4", new TemplateData(meal.getDuration()+"小时", "#565656"));
                    param.put("thing5", new TemplateData("用户申请取消订单,请及时沟通确认,谢谢", "#ff9662"));
//                    param.put("remark", new TemplateData("点击查看详情", "#ff9662"));
                    String notifyUrl = wxpayDomain + "pages/order/orderDetail?orderId="+order.getId();
                    JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(param));
                    String suc = WXSubscribeMsgUtil.sendWechatMsgToUser(member.getWeixinOpenid(), templateId, notifyUrl, jsonObject, accessToken);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Async
    @Override
    public void sendDasaoMsg(DmsOrder order) {
        QsgStore store = storeService.getById(order.getStoreId());
        String accessToken = null;
        try {
            QueryWrapper qw = new QueryWrapper();
            qw.eq("store_id",order.getStoreId());
            List<UmsAdminMember> members = adminMemberService.list(qw);
            accessToken = redisService.get("wx_accesstoken");
            String templateId = store.getTemplateIdComplete();
            QsgDevice device = deviceService.getById(order.getDeviceId());
            Map<String, TemplateData> param = new HashMap<>();
            String time = order.getEndTime();
//            QsgMeal meal = mealService.getById(order.getMealId());
            if (null!=members&&members.size()>0){
                for (UmsAdminMember member : members
                ) {
//                    param.put("first", new TemplateData("房间:"+device.getMachineName()+" 已完成订单", "#565656"));
                    param.put("character_string8", new TemplateData(order.getOrderSn(), "#565656"));
                    param.put("time24", new TemplateData(time, "#565656"));
                    param.put("thing17", new TemplateData(device.getMachineName(), "#ff9662"));
                    JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(param));
                    String suc = WXSubscribeMsgUtil.sendWechatMsgToUser(member.getWeixinOpenid(), templateId, "", jsonObject, accessToken);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Async
    @Override
    public void sendRecharge(QsgRechargeOrder order,Integer integral) {
        QsgStore store = storeService.getById(order.getStoreId());
        String accessToken = null;
        try {
            QueryWrapper qw = new QueryWrapper();
            qw.eq("store_id",order.getStoreId());
            List<UmsAdminMember> members = adminMemberService.list(qw);
            accessToken = redisService.get("wx_accesstoken");
            String templateId = store.getTemplateIdChongzhi();
            Map<String, TemplateData> param = new HashMap<>();
            UmsMember user = memberService.getById(order.getMemberId());
            if (null!=members&&members.size()>0){
                for (UmsAdminMember member : members
                ) {
                    param.put("thing8", new TemplateData(user.getNickname(), "#565656"));
                    param.put("amount2", new TemplateData(order.getPrice().toString(), "#565656"));
                    param.put("time4", new TemplateData(DateUtil.dateToString(order.getCreateDatetime()), "#565656"));
                    JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(param));
                    String suc = WXSubscribeMsgUtil.sendWechatMsgToUser(member.getWeixinOpenid(), templateId, "", jsonObject, accessToken);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
